const webpack = require('webpack')
const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')

class MyPlugin {
  apply(compiler) {
    console.log('my plugin 启动')
    compiler.hooks.emit.tap('MyPlugin', compilation => {
      for (const name in compilation.assets) {
        if (name.endsWith('.js')) {
          const contents = compilation.assets[name].source()
          const withoutComments = contents.replace(/\/\*\*+\*\//g, '')
          compilation.assets[name] = {
            source: () => withoutComments,
            size: () => withoutComments.length
          }
        }
      }
    })
  }
}
module.exports = {
  // 开发模式
  mode: 'none',
  // 入口
  entry: './src/main.js',
  // 输出
  output: {
    filename: "main.js",
    path: path.join(__dirname, 'dist'),
    // 改变找资源的路径，默认是根目录
    // publicPath: "dist/"
  },
  // 配置辅助工具
  // devtool: "source-map", // 在dist里生成map文件
  devtool: "eval", // 不生成map文件，生成文件路径
  // 为webpack dev server
  devServer: {
    // 指定静态资源访问
    // contentBase: 'public',
    // 代理
    proxy: {
      '/users': {
        target: 'https://api.github.com',
        // pathRewrite: {
        //   '^/api': ''
        // },
        changeOrigin: true
      }
    },
    // 热替换
    // hot: true
    hotOnly: true
  },
  // 模块加载器
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },
      {
        test: /\.png$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10 * 1024 // 超过10K的单独存放
          }
        }
      },
      {
        test: /\.html$/,
        use: {
          loader: "html-loader",
          // options: {
          //   attrs: ['img:src', 'a:href']
          // }
        }
      },
      {
        test: /\.md$/,
        use: [
          'html-loader',
          './markdown-loader' // 顺序是从后往前执行
        ]
      }
    ]
  },
  plugins: [
    // 先清理再生成dist，生产模式用
    // new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: "Webpack Plugin Sample",
      meta: {
        viewport: 'width=device-width',
      },
      template: "./src/index.html"
    }),
    new HtmlWebpackPlugin({
      filename: "about.html"
    }),
    // 静态文件替换，生产模式用
    // new CopyWebpackPlugin({
    //   patterns: [
    //     'public'
    //   ]
    // }),
    new MyPlugin(),
    // 热替换
    new webpack.HotModuleReplacementPlugin()
  ]
}
